package com.ruoyi.eqmonitor.config;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 配置dev环境不启动gateway获取用户信息
 */
@Order(0)
@Profile("dev")
//@Configuration
@Deprecated
public class WebAppConfigurer implements WebMvcConfigurer {
    private static final Logger log = LoggerFactory.getLogger(WebAppConfigurer.class);

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(devUserInterceptor()).addPathPatterns("/**");
    }

    public HandlerInterceptor devUserInterceptor() {
        return new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//                String token = SecurityUtils.getToken();
//                if (StringUtils.isEmpty(token)) {
//                    log.debug("无法获取当前登录用户的令牌");
//                    return true;
//                }
//
//                // JWT解析
//                Claims claims = JwtUtils.parseToken(token);
//                if (claims == null) {
//                    log.debug("无效的JWT令牌");
//                    return true;
//                }
//
//
//                TokenService tokenService = SpringUtils.getBean(TokenService.class);
//                LoginUser loginUser = tokenService.getLoginUser(token);
//                // 注入线程上下文对象
//                SecurityContextHolder.setUserId(JwtUtils.getUserId(claims));
//                SecurityContextHolder.setUserName(JwtUtils.getUserName(claims));
//                SecurityContextHolder.setUserKey(JwtUtils.getUserKey(claims));
//                SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
                return true;
            }
        };
    }
}
